import { pool } from '../config/database';

export interface UploadFile {
  id?: number;
  filename: string;
  originalname: string;
  mimetype: string;
  size: number;
  path: string;
  created_at?: Date;
}

export class UploadModel {
  // 创建文件记录
  static async create(file: UploadFile): Promise<number> {
    const [result] = await pool.execute(
      'INSERT INTO uploads (filename, originalname, mimetype, size, path) VALUES (?, ?, ?, ?, ?)',
      [file.filename, file.originalname, file.mimetype, file.size, file.path],
    );
    return (result as any).insertId;
  }

  // 获取所有文件记录
  static async findAll(): Promise<UploadFile[]> {
    const [rows] = await pool.execute('SELECT * FROM uploads ORDER BY created_at DESC');
    return rows as UploadFile[];
  }

  // 根据ID获取文件记录
  static async findById(id: number): Promise<UploadFile | null> {
    const [rows] = await pool.execute('SELECT * FROM uploads WHERE id = ?', [id]);
    const files = rows as UploadFile[];
    return files.length > 0 ? files[0] : null;
  }

  // 删除文件记录
  static async delete(id: number): Promise<boolean> {
    const [result] = await pool.execute('DELETE FROM uploads WHERE id = ?', [id]);
    return (result as any).affectedRows > 0;
  }
}
